import { Repository } from 'typeorm';
import { CartEntity } from './entities/shop-cart.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { ProductService } from '../products/product.service';
import { CreateCartDto, UpdateCartDto } from './dto/shop-cart.dto';
import { ResultData } from 'src/common/utils/result';
import { NotFoundException } from '@nestjs/common';

export class CartService {
  constructor(
    @InjectRepository(CartEntity)
    private readonly cartRepo: Repository<CartEntity>,
    private readonly productService: ProductService,
  ) {}
  async addCart(data: CreateCartDto) {
    const { userId, productId, quantity } = data;
    const { data: product } = await this.productService.findOne(productId);
    if (!product) {
      throw new Error('商品不存在');
    }
    let cartItem = await this.cartRepo.findOneBy({ userId, productId });
    if (cartItem) {
      cartItem.quantity += quantity;
    } else {
      cartItem = this.cartRepo.create({
        userId,
        productId,
        quantity,
        productName: product.name,
        image: product.mianImage,
        price: product.price,
        selected: true,
      });
    }

    await this.cartRepo.save(cartItem);
    return ResultData.ok('添加成功');
  }

  async updateCart(data: UpdateCartDto) {
    const { id, ...rest } = data;
    const cartItem = await this.cartRepo.findOneBy({ id });
    if (!cartItem) {
      throw new NotFoundException('当前实体不存在');
    }
    await this.cartRepo.update(id, rest);
    return ResultData.ok('操作成功');
  }

  async findAll(userId: number) {
    const carts = await this.cartRepo.find({ where: { userId } });
    return ResultData.ok(carts);
  }
}
